package com.nengchuan.eic.nceconomy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eic.psm.sdk.entity.CoreSection;
import com.eic.psm.sdk.vo.CoreSectionDepartInfoVo;
import com.eic.review.sdk.vo.TechnoProjectInfoVo;
import com.nengchuan.eic.nceconomy.constant.CommonConstant;
import com.nengchuan.eic.nceconomy.constant.DepartInfoEnum;
import com.nengchuan.eic.nceconomy.constant.RoleEnum;
import com.nengchuan.eic.nceconomy.dao.ProjectRoleMapper;
import com.nengchuan.eic.nceconomy.dao.RoleMangeMapper;
import com.nengchuan.eic.nceconomy.dao.RoleMapper;
import com.nengchuan.eic.nceconomy.dao.UserRoleMapper;
import com.nengchuan.eic.nceconomy.entity.dto.RoleDistributionDTO;
import com.nengchuan.eic.nceconomy.entity.po.ProjectRole;
import com.nengchuan.eic.nceconomy.entity.po.UserRole;
import com.nengchuan.eic.nceconomy.entity.vo.*;
import com.nengchuan.eic.nceconomy.fegin.ProcessFeignTechnicalCassicsService;
import com.nengchuan.eic.nceconomy.util.IdSequence;
import com.nsc.boot.common.sdk.msg.ApiResult;
import com.nsc.boot.common.sdk.vo.IPage;
import com.nsc.boot.common.utils.page.PageQuery;
import com.nsc.boot.sdk.common.utils.AuthUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能描述:
 *
 * @Author: liurui
 * @Date: 2020/5/15 0015 下午 3:07
 */
@Service
public class RoleMangeServiceImpl implements RoleMangeService {

    @Autowired
    private RoleMangeMapper roleMangeMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private ProjectRoleMapper projectRoleMapper;

    @Autowired
    private ProcessFeignTechnicalCassicsService processFeignTechnicalCassicsService;


    @Override
    public String distribution(RoleDistributionDTO roleDistributionDTO) {
//        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("role_code","NCECONOMY_PRINCIPAL");
//        List<Role> roles = roleMapper.selectList(queryWrapper);
//        Role role=null;
//        if(CollectionUtils.isNotEmpty(roles)){
//            role=roles.get(0);
//        }
        UserRole userRole = new UserRole();
        userRole.setId(IdSequence.generateId());
        userRole.setUserId(roleDistributionDTO.getUserId());
        userRole.setRoleId(roleDistributionDTO.getRoleId());
        userRole.setOrgId(roleDistributionDTO.getOrgId());
        userRole.setUserName(roleDistributionDTO.getUserName());
        userRole.setLoginName(roleDistributionDTO.getLoginName());
        userRole.setMobile(roleDistributionDTO.getMobile());
        userRole.setOrgCategory(roleDistributionDTO.getOrgCategoryCode());
        userRole.setCreateId(AuthUtil.getUserId()==null?0:AuthUtil.getUserId());
        userRole.setCreateName(AuthUtil.getRealName()==null?"admin":AuthUtil.getRealName());
        userRole.setCreateTime(System.currentTimeMillis());
        userRoleMapper.insert(userRole);

        return "成功";
    }

    @Override
    public List<OrgRole> getRoleListInfo(Long orgId) {
        return roleMangeMapper.getRoleListInfo(orgId);
    }

    @Override
    public String delete(RoleDistributionDTO roleDistributionDTO) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",roleDistributionDTO.getRoleId());
        queryWrapper.eq("org_id",roleDistributionDTO.getOrgId());
        queryWrapper.eq("user_id",roleDistributionDTO.getUserId());
        userRoleMapper.delete(queryWrapper);
        return "成功";
    }

    @Override
    public String deleteOnProject(RoleDistributionDTO roleDistributionDTO) {
        QueryWrapper<ProjectRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id",roleDistributionDTO.getProId());
        queryWrapper.eq("duty_user_id",roleDistributionDTO.getUserId());
        queryWrapper.eq("type",roleDistributionDTO.getType());
        projectRoleMapper.delete(queryWrapper);
        return "成功";
    }

    @Override
    public String distributionProject(RoleDistributionDTO roleDistributionDTO) {
        ProjectRole projectRole=new ProjectRole();
        projectRole.setId(IdSequence.generateId());
        projectRole.setProjectId(roleDistributionDTO.getProId());
        projectRole.setDutyUserId(roleDistributionDTO.getUserId());
        projectRole.setDutyUserName(roleDistributionDTO.getUserName());
        projectRole.setType(roleDistributionDTO.getType());
        projectRole.setDelFlag(0);
        projectRole.setCreateId(AuthUtil.getUserId()==null?0:AuthUtil.getUserId());
        projectRole.setCreateName(AuthUtil.getRealName()==null?"admin":AuthUtil.getRealName());
        projectRole.setCreateTime(System.currentTimeMillis());
        projectRoleMapper.insert(projectRole);
        return "成功";
    }

    @Override
    public Map<String ,List<DutyInfoVO>> getDutyList(Long orgId) {
        List<DutyInfoVO> dutyList = roleMangeMapper.getDutyList(orgId);
        Map<String ,List<DutyInfoVO>> map=new HashMap<>();
        map.put("ROLE_NCECONOMY_DUTY",CollectionUtils.isNotEmpty(dutyList)?dutyList.stream().filter(x->RoleEnum.ROLE_NCECONOMY_CIRCUIT_DUTY.name().equals(x.getRoleCode())||RoleEnum.ROLE_NCECONOMY_POWER_DUTY.name().equals(x.getRoleCode())).collect(Collectors.toList()):null);
        map.put("ROLE_TECHNOLOGY_DUTY",CollectionUtils.isNotEmpty(dutyList)?dutyList.stream().filter(x->RoleEnum.ROLE_TECHNOLOGY_POWER_DUTY.name().equals(x.getRoleCode())||RoleEnum.ROLE_TECHNOLOGY_CIRCUIT_DUTY.name().equals(x.getRoleCode())).collect(Collectors.toList()):null);

        return map;
    }

    @Override
    public List<CoreSectionVO> getCoreSectionInfo(List<CoreSection> coreSection, List<CoreSectionDepartInfoVo> departInfo) {
        List<CoreSectionVO> coreSectionVoS=new ArrayList<>(coreSection.size());

        //部门信息
        coreSection.forEach(x->{
            CoreSectionVO coreSectionVO = new CoreSectionVO(x);
            coreSectionVoS.add(coreSectionVO);
            //查找监理单位技经主管
            if(x.getSupervisionUnitId()!=null){
                UserRole userRole=userRoleMapper.getRoleInfoByOrgIdAndRole(x.getSupervisionUnitId(), "ROLE_NCECONOMY_MANAGER");
                DepartInfo departInfo1 = new DepartInfo();
                departInfo1.setId(5L);
                departInfo1.setDepartName(DepartInfoEnum.OWNER_DEPART.getText());
                departInfo1.setMobile(userRole.getMobile());
                departInfo1.setUserName(userRole.getUserName());
                coreSectionVO.getDepartInfoList().add(departInfo1);
            }
            departInfo.forEach(y->{
                if(x.getId().equals(y.getId())){
                    coreSectionVO.getDepartInfoList().add(new DepartInfo(y));
                }
            });
            coreSectionVO.setDepartInfoList(coreSectionVO.getDepartInfoList().stream().filter(y-> StringUtils.isNotBlank(y.getDepartName())).sorted(Comparator.comparing(DepartInfo::getDepartId).reversed()).collect(Collectors.toList()));
        });

        return coreSectionVoS;
    }

    @Override
    public List<ProjectInfo> getTechnoProjectInfo(Long projectId) {
        List<ProjectInfo> list=new ArrayList<>();

        //省公司
        ProjectInfo projectInfo=new ProjectInfo();
        projectInfo.setCompanyCategoryName("省公司");
        List<ProjectInfo.Person> roleInfoByOrgIdOrOrgCode = userRoleMapper.getRoleInfoByOrgIdOrOrgCode(null, CommonConstant.CompanyCategory.PROVINCE_COMPANY);
        List<ProjectInfo.Person> list1 = getPeople(roleInfoByOrgIdOrOrgCode);
        projectInfo.setPersonList(list1);
        //建管单位
        ApiResult<TechnoProjectInfoVo> technoProjectInfo =
                processFeignTechnicalCassicsService.getTechnoProjectInfo(projectId);
        ProjectInfo projectInfo1=new ProjectInfo();
        projectInfo1.setCompanyCategoryName("建管单位");
        if(CommonConstant.responseCode.SUCCESS==technoProjectInfo.getCode()&&technoProjectInfo.getData()!=null){
            TechnoProjectInfoVo data = technoProjectInfo.getData();
            if(data.getBuildUnitId()!=null){
                projectInfo1.setCompanyName(data.getBuildUnitName());
                List<ProjectInfo.Person> roleInfoByOrgIdOrOrgCode1 = userRoleMapper.getRoleInfoByOrgIdOrOrgCode(data.getBuildUnitId(), null);
                List<ProjectInfo.Person> list2 = getPeople(roleInfoByOrgIdOrOrgCode1);
                projectInfo1.setPersonList(list2);
            }
        }
        //设计单位
        ProjectInfo projectInfo2=new ProjectInfo();
        projectInfo2.setCompanyCategoryName("设计单位");
        if(CommonConstant.responseCode.SUCCESS==technoProjectInfo.getCode()&&technoProjectInfo.getData()!=null){
            TechnoProjectInfoVo data = technoProjectInfo.getData();
            projectInfo2.setCompanyName(data.getDesignUnitName());
            List<ProjectInfo.Person> roleInfoByOrgIdOrOrgCode3=new ArrayList<>();
            if(data.getBuildUnitResponsibleId()!=null){
                ProjectInfo.Person person = new ProjectInfo.Person();
                person.setRoleName("设总");
                person.setUserName(data.getDesignUnitResponsibleName());
                person.setUserId(data.getDesignUnitResponsibleId());
                roleInfoByOrgIdOrOrgCode3.add(person);
            }
            if(CollectionUtils.isNotEmpty(data.getUserVoList())){
                data.getUserVoList().forEach(x->{
                    ProjectInfo.Person person = new ProjectInfo.Person();
                    person.setRoleName(x.getMajor());
                    person.setUserName(x.getName());
                    person.setUserId(x.getId());
                    roleInfoByOrgIdOrOrgCode3.add(person);
                });
            }
            projectInfo2.setPersonList(roleInfoByOrgIdOrOrgCode3);
        }
        list.add(projectInfo);
        list.add(projectInfo1);
        list.add(projectInfo2);
        return list;
    }

    private List<ProjectInfo.Person> getPeople(List<ProjectInfo.Person> roleInfoByOrgIdOrOrgCode) {
        Map<Long, List<ProjectInfo.Person>> collect = roleInfoByOrgIdOrOrgCode.stream().collect(Collectors.groupingBy(ProjectInfo.Person::getRoleId));
        List<ProjectInfo.Person> list1=new ArrayList<>();
        for(Long s:collect.keySet()){
            List<ProjectInfo.Person> people = collect.get(s);
            String userName = people.stream().map(ProjectInfo.Person::getUserName).collect(Collectors.joining("、"));
            ProjectInfo.Person person = new ProjectInfo.Person();
            person.setUserName(userName);
            person.setRoleName(people.get(0).getRoleName());
            person.setRoleId(people.get(0).getRoleId());
            list1.add(person);
        }
        return list1;
    }

    @Override
    public IPage<OrgProject> getTechnoProjectList(PageQuery pageQuery, Integer unitType, String projectName, Long unitId, String erpCode, String projectStage) {
        ApiResult<IPage<TechnoProjectVO>> technoProjectList = processFeignTechnicalCassicsService.getTechnoProjectList(pageQuery.getSize(),pageQuery.getCurrent(), unitType, projectName, unitId, erpCode,projectStage);

//        //查询专责人员
//        List<String> roleNceconomyPowerDuty = roleMangeMapper.getRoleNceconomyDutyByOrgId(unitId,RoleEnum.ROLE_NCECONOMY_POWER_DUTY.name());
//        List<String> roleNceconomyCircuitDuty = roleMangeMapper.getRoleNceconomyDutyByOrgId(unitId,RoleEnum.ROLE_NCECONOMY_CIRCUIT_DUTY.name());
//        List<String> roleTechnologyCircuitDuty = roleMangeMapper.getRoleNceconomyDutyByOrgId(unitId,RoleEnum.ROLE_TECHNOLOGY_CIRCUIT_DUTY.name());
//        List<String> roleTechnologyPowerDuty = roleMangeMapper.getRoleNceconomyDutyByOrgId(unitId,RoleEnum.ROLE_TECHNOLOGY_POWER_DUTY.name());



        if(technoProjectList!=null&&CommonConstant.responseCode.SUCCESS==technoProjectList.getCode()){
            IPage<TechnoProjectVO> data = technoProjectList.getData();
            List<TechnoProjectVO> records = data.getRecords();
            List<OrgProject> list=new ArrayList<>();
            records.forEach(x->{
                OrgProject orgProject = new OrgProject(x);
                if(CollectionUtils.isNotEmpty(orgProject.getProjectLists())){
                    orgProject.getProjectLists().forEach(y->{
                        List<DutyVO> roleNceconomyDutyByProjectId = roleMangeMapper.getRoleNceconomyDutyByProjectId(y.getProjectId());
                        if(CollectionUtils.isNotEmpty(roleNceconomyDutyByProjectId)){
                            y.setRoleNceconomyDuty(roleNceconomyDutyByProjectId.stream().filter(z -> "1".equals(z.getType())).collect(Collectors.toList()));
                            y.setRoleTechnologyDuty(roleNceconomyDutyByProjectId.stream().filter(z -> "2".equals(z.getType())).collect(Collectors.toList()));
                        }
                    });
                }
                list.add(orgProject);
            });

            IPage<OrgProject> orgProjectIPage = new IPage<>();
            orgProjectIPage.setCurrent(pageQuery.getCurrent());
            orgProjectIPage.setRecords(list);
            orgProjectIPage.setSize(pageQuery.getSize());
            orgProjectIPage.setTotal(data.getTotal());
            return orgProjectIPage;
        }
        return null;
    }


}
